package com.kws.merchant.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author : zhangbenting
 * @date : 2024/11/7 10:09
 * @Version: 1.0
 */
@Service
public class RedisLockService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 尝试获取锁
     *
     * @param lockKey   锁的 key
     * @param lockValue 锁的唯一标识
     * @param timeout   锁的超时时间
     * @return 获取锁成功与否
     */
    public boolean acquireLock(String lockKey, String lockValue, long timeout) {
        Boolean result = redisTemplate.opsForValue().setIfAbsent(lockKey, lockValue, timeout, TimeUnit.MILLISECONDS);
        return result != null && result;
    }

    /**
     * 释放锁
     *
     * @param lockKey   锁的 key
     * @param lockValue 锁的唯一标识
     */
    public void releaseLock(String lockKey, String lockValue) {
        String currentLockValue = redisTemplate.opsForValue().get(lockKey);
        if (lockValue.equals(currentLockValue)) {
            redisTemplate.delete(lockKey);
        }
    }

}
